<template>
  <div class="page-container">
    <!-- 搜索头部 -->
    <div class="search-header">
      <div class="search-input-wrapper">
        <Find class="search-icon" />
        <input 
          v-model="searchKeyword" 
          type="text" 
          placeholder="搜索商品"
          class="search-input"
          @input="handleSearch"
          @keyup.enter="performSearch"
        />
        <span class="clear-btn" v-if="searchKeyword" @click="clearSearch">×</span>
      </div>
      <span class="cancel-btn" @click="goBack">取消</span>
    </div>

    <!-- 搜索内容 -->
    <div class="search-content" v-if="!searchKeyword">
      <!-- 搜索历史 -->
      <div class="search-history" v-if="searchHistory.length">
        <div class="section-header">
          <h3>搜索历史</h3>
          <span class="clear-history" @click="clearHistory">清空</span>
        </div>
        <div class="history-tags">
          <span 
            class="history-tag" 
            v-for="(item, index) in searchHistory" 
            :key="index"
            @click="searchByHistory(item)"
          >
            {{ item }}
          </span>
        </div>
      </div>

      <!-- 热门搜索 -->
      <div class="hot-search">
        <div class="section-header">
          <h3>热门搜索</h3>
        </div>
        <div class="hot-tags">
          <span 
            class="hot-tag" 
            v-for="(item, index) in hotSearch" 
            :key="index"
            @click="searchByHistory(item)"
          >
            {{ item }}
          </span>
        </div>
      </div>

      <!-- 推荐商品 -->
      <div class="recommend-products">
        <div class="section-header">
          <h3>为您推荐</h3>
        </div>
        <div class="product-grid">
          <div 
            class="product-card" 
            v-for="product in recommendProducts" 
            :key="product.id"
            @click="goToProduct(product.id)"
          >
            <div class="product-image">
              <img :src="product.image" :alt="product.name" />
            </div>
            <div class="product-info">
              <h4 class="product-name">{{ product.name }}</h4>
              <div class="product-price">
                <span class="current-price">¥{{ product.price }}</span>
                <span class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div class="search-results" v-else>
      <div class="result-header">
        <span class="result-count">找到 {{ searchResults.length }} 个相关商品</span>
        <div class="sort-options">
          <span 
            class="sort-option" 
            :class="{ active: sortBy === 'default' }"
            @click="sortBy = 'default'"
          >
            综合
          </span>
          <span 
            class="sort-option" 
            :class="{ active: sortBy === 'sales' }"
            @click="sortBy = 'sales'"
          >
            销量
          </span>
          <span 
            class="sort-option" 
            :class="{ active: sortBy === 'price' }"
            @click="sortBy = 'price'"
          >
            价格
          </span>
        </div>
      </div>

      <div class="result-list" v-if="searchResults.length">
        <div 
          class="result-item" 
          v-for="product in sortedResults" 
          :key="product.id"
          @click="goToProduct(product.id)"
        >
          <div class="product-image">
            <img :src="product.image" :alt="product.name" />
          </div>
          <div class="product-info">
            <h4 class="product-name">{{ product.name }}</h4>
            <p class="product-desc">{{ product.description }}</p>
            <div class="product-meta">
              <span class="sales">销量 {{ product.sales }}件</span>
              <span class="rating">评分 {{ product.rating }}分</span>
            </div>
            <div class="product-price">
              <span class="current-price">¥{{ product.price }}</span>
              <span class="original-price" v-if="product.originalPrice">¥{{ product.originalPrice }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="empty-results" v-else>
        <img src="https://picsum.photos/80/80?random=1" alt="无搜索结果" />
        <h3>没有找到相关商品</h3>
        <p>试试其他关键词吧</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Find } from '@nutui/icons-vue'

const router = useRouter()

// 搜索关键词
const searchKeyword = ref('')

// 排序方式
const sortBy = ref('default')

// 搜索历史
const searchHistory = ref(['iPhone', '华为', '小米', 'MacBook', 'AirPods'])

// 热门搜索
const hotSearch = ref(['手机', '电脑', '耳机', '手表', '平板', '充电器', '数据线'])

// 推荐商品
const recommendProducts = ref([
  {
    id: 1,
    name: 'iPhone 15 Pro',
    price: 7999,
    originalPrice: 8999,
    image: 'https://picsum.photos/120/120?random=1'
  },
  {
    id: 2,
    name: '华为 Mate 60',
    price: 6999,
    originalPrice: 7999,
    image: 'https://picsum.photos/120/120?random=1'
  },
  {
    id: 3,
    name: '小米 14 Ultra',
    price: 5999,
    image: 'https://picsum.photos/120/120?random=1'
  },
  {
    id: 4,
    name: 'MacBook Pro M3',
    price: 14999,
    image: 'https://picsum.photos/120/120?random=1'
  }
])

// 搜索结果
const searchResults = ref([])

// 模拟搜索结果
const mockSearchResults = [
  {
    id: 1,
    name: 'iPhone 15 Pro Max 256GB',
    price: 9999,
    originalPrice: 10999,
    description: '搭载A17 Pro芯片，性能强劲，拍照效果出色',
    sales: 12580,
    rating: 4.8,
    image: 'https://picsum.photos/120/120?random=1'
  },
  {
    id: 2,
    name: '华为 Mate 60 Pro 512GB',
    price: 6999,
    originalPrice: 7999,
    description: '麒麟芯片，卫星通信，徕卡影像',
    sales: 8960,
    rating: 4.9,
    image: 'https://picsum.photos/120/120?random=1'
  },
  {
    id: 3,
    name: '小米 14 Ultra 16GB+1TB',
    price: 5999,
    description: '骁龙8 Gen3，徕卡光学，2K屏幕',
    sales: 6540,
    rating: 4.7,
    image: 'https://picsum.photos/120/120?random=1'
  }
]

// 排序后的结果
const sortedResults = computed(() => {
  if (sortBy.value === 'default') {
    return searchResults.value
  } else if (sortBy.value === 'sales') {
    return [...searchResults.value].sort((a, b) => b.sales - a.sales)
  } else if (sortBy.value === 'price') {
    return [...searchResults.value].sort((a, b) => a.price - b.price)
  }
  return searchResults.value
})

// 处理搜索输入
const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    performSearch()
  }
}

// 执行搜索
const performSearch = () => {
  const keyword = searchKeyword.value.trim()
  if (!keyword) return

  // 模拟搜索
  searchResults.value = mockSearchResults.filter(product => 
    product.name.toLowerCase().includes(keyword.toLowerCase()) ||
    product.description.toLowerCase().includes(keyword.toLowerCase())
  )

  // 添加到搜索历史
  if (!searchHistory.value.includes(keyword)) {
    searchHistory.value.unshift(keyword)
    if (searchHistory.value.length > 10) {
      searchHistory.value.pop()
    }
  }
}

// 清空搜索
const clearSearch = () => {
  searchKeyword.value = ''
  searchResults.value = []
}

// 清空历史
const clearHistory = () => {
  searchHistory.value = []
}

// 通过历史记录搜索
const searchByHistory = (keyword) => {
  searchKeyword.value = keyword
  performSearch()
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 跳转到商品详情
const goToProduct = (productId) => {
  router.push(`/product-detail/${productId}`)
}

onMounted(() => {
  // 页面加载完成后的逻辑
})
</script>

<style scoped>
.search-header {
  background: white;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  position: sticky;
  top: 0;
  z-index: 100;
  border-bottom: 1px solid #f0f0f0;
}

.search-input-wrapper {
  flex: 1;
  position: relative;
  display: flex;
  align-items: center;
  background: #f5f5f5;
  border-radius: 20px;
  padding: 8px 16px;
}

.search-icon {
  color: #999;
  font-size: 16px;
  margin-right: 8px;
}

.search-input {
  flex: 1;
  border: none;
  background: transparent;
  outline: none;
  font-size: 14px;
  color: #333;
}

.search-input::placeholder {
  color: #999;
}

.clear-btn {
  color: #999;
  font-size: 18px;
  cursor: pointer;
  padding: 4px;
}

.cancel-btn {
  font-size: 14px;
  color: #666;
  cursor: pointer;
  white-space: nowrap;
}

.search-content {
  flex: 1;
  padding: 20px 16px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h3 {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.clear-history {
  font-size: 12px;
  color: #666;
  cursor: pointer;
}

.history-tags, .hot-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 32px;
}

.history-tag, .hot-tag {
  background: #f0f0f0;
  color: #333;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
}

.history-tag:hover, .hot-tag:hover {
  background: #e0e0e0;
}

.recommend-products {
  margin-top: 32px;
}

.product-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.product-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
}

.product-image {
  height: 120px;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  padding: 12px;
}

.product-name {
  font-size: 12px;
  color: #333;
  margin: 0 0 8px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-price {
  display: flex;
  align-items: center;
  gap: 8px;
}

.current-price {
  font-size: 14px;
  font-weight: 600;
  color: #ff4757;
}

.original-price {
  font-size: 10px;
  color: #999;
  text-decoration: line-through;
}

.search-results {
  flex: 1;
}

.result-header {
  background: white;
  padding: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f0f0f0;
}

.result-count {
  font-size: 14px;
  color: #666;
}

.sort-options {
  display: flex;
  gap: 20px;
}

.sort-option {
  font-size: 14px;
  color: #666;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  transition: all 0.3s;
}

.sort-option.active {
  color: #ff4757;
  background: rgba(255, 71, 87, 0.1);
}

.result-list {
  background: white;
}

.result-item {
  display: flex;
  gap: 12px;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.result-item:last-child {
  border-bottom: none;
}

.result-item .product-image {
  width: 120px;
  height: 120px;
  flex-shrink: 0;
}

.result-item .product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.result-item .product-info {
  flex: 1;
  padding: 0;
}

.result-item .product-name {
  font-size: 16px;
  margin-bottom: 6px;
}

.product-desc {
  font-size: 12px;
  color: #666;
  margin: 0 0 8px 0;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 8px;
}

.sales, .rating {
  font-size: 12px;
  color: #999;
}

.empty-results {
  text-align: center;
  padding: 80px 20px;
  color: #999;
}

.empty-results img {
  width: 80px;
  height: 80px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-results h3 {
  font-size: 18px;
  color: #666;
  margin: 0 0 8px 0;
}

.empty-results p {
  font-size: 14px;
  color: #999;
  margin: 0;
}
</style>
